from datetime import datetime
import os
import re

from app.ext import db
from app.models import PDMFileModel, PDMModuleModel, PDMTableModel, PDMColumnModel
from app.utils.PDMParser import PDMParser


class PDMHandler:
    def __init__(self, pdm_folder='pdm', pdm_dir=None):
        self.pdm_folder = pdm_folder
        self.PDM_DIR = pdm_dir or r'\PDMReadWeb\pdm'

    def load_pdm(self, file_path, with_columns: bool = False):
        parser = PDMParser()
        return parser.parse(file_path, with_columns=with_columns)

    def _parse_datetime(self, date_str, format_str="%Y-%m-%d %H:%M:%S"):
        """解析时间字符串为 datetime 对象"""
        try:
            return datetime.strptime(date_str, format_str) if isinstance(date_str, str) else None
        except ValueError:
            print(f"警告：无法解析时间字符串 {date_str}")
            return None

    def _parse_timestamp(self, timestamp_str):
        """解析时间戳字符串为 datetime 对象"""
        try:
            return datetime.fromtimestamp(int(timestamp_str)) if timestamp_str.isdigit() else None
        except (ValueError, OverflowError):
            print(f"警告：无法解析时间戳 {timestamp_str}")
            return None

    def _extract_chinese_name(self, table_name):
        """从表名中提取中文名称"""
        CHINESE_NAME_REGEX = r'\((.*?)\)'
        match = re.search(CHINESE_NAME_REGEX, table_name)
        return match.group(1) if match else ''

    def import_all_to_db(self):
        try:
            # 获取 PDM 文件列表
            if not os.path.exists(self.PDM_DIR):
                raise FileNotFoundError(f"路径 {self.PDM_DIR} 不存在")
            pdm_files = [f for f in os.listdir(self.PDM_DIR) if f.endswith('.pdm')]

            # 批量导入
            for f in pdm_files:
                print(f"📄 正在解析文件: {f}")
                file_path = os.path.join(self.PDM_DIR, f)
                if not os.access(file_path, os.R_OK):
                    print(f" 警告：无法读取文件 {f}")
                    continue

                pdm = self.load_pdm(file_path, with_columns=True)

                # 提取文件基本信息
                name = pdm.name
                table_count = len(pdm.tables)
                database_type = pdm.database_type
                file_md5 = pdm.file_md5
                file_modify_time = self._parse_datetime(pdm.file_modify_time)
                file_size = int(pdm.file_size)

                # 创建 PDM 文件记录
                file_model = PDMFileModel(
                    file_name=name,
                    database_type=database_type,
                    file_md5=file_md5,
                    file_modify_time=file_modify_time,
                    file_size=file_size,
                    table_count=table_count
                )
                db.session.add(file_model)
                db.session.flush()  # 获取 file_model.id

                # 保存模块信息
                for module in pdm.physical_diagrams:
                    module_model = PDMModuleModel(
                        m_objectId=module.mid,
                        m_name=module.m_name,
                        m_code=module.m_code,
                        phy_objectId=module.phy_id,
                        phy_name=module.phy_name,
                        phy_code=module.phy_code,
                        table_ids=module.tables,
                        pdm_id=file_model.fid
                    )
                    db.session.add(module_model)

                # 保存表和字段信息
                for table in pdm.tables.values():
                    name_zh = self._extract_chinese_name(table.t_name)
                    creation_date = self._parse_timestamp(table.t_creationDate)
                    modification_date = self._parse_timestamp(table.t_modificationDate)

                    table_model = PDMTableModel(
                        table_id=table.tid,
                        name=name_zh,
                        code=table.t_code,
                        objectId=table.t_objectId,
                        creationDate=creation_date,
                        creator=table.t_creator,
                        modificationDate=modification_date,
                        modifier=table.t_modifier,
                        owner=table.t_code,
                        pdm_id=file_model.fid
                    )
                    db.session.add(table_model)

                    for column in table.columns:
                        column_model = PDMColumnModel(
                            objectId=column.oid,
                            name=column.name,
                            code=column.code,
                            data_type=column.data_type,
                            default=column.default,
                            length=column.length,
                            mandatory=column.mandatory,
                            comment=column.comment,
                            table_id=table.tid,
                            pdm_id=file_model.fid
                        )
                        db.session.add(column_model)

            # 最终提交事务
            db.session.commit()
            print("🎉 所有 PDM 文件导入完成")

        except Exception as e:
            db.session.rollback()
            print(f" 错误：导入失败，原因: {e}")
